package cn.openea.perpartner.payment.web.points.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.openea.perpartner.common.core.text.Convert;
import cn.openea.perpartner.common.core.utils.Arith;
import cn.openea.perpartner.common.redis.service.RedisCache;
import cn.openea.perpartner.payment.web.points.entity.RateCenter;
import cn.openea.perpartner.payment.web.points.mapper.RateCenterMapper;
import cn.openea.perpartner.payment.web.points.service.IRateCenterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * (PaymentRateCenter)表服务实现类
 *
 * @author Weird077
 * @since 2022-10-31 08:59:10
 */
@Slf4j
@Service("paymentRateCenterService")
public class RateCenterServiceImpl extends ServiceImpl<RateCenterMapper, RateCenter> implements IRateCenterService {
    @Resource
    private RedisCache redisCache;
    @Value("${growth.redis.expire}")
    private long expireTime;

    @Override
    public double getRate(String sceneId) {
        String rateVale = Convert.toStr(redisCache.getCacheObject(getCacheKey(sceneId)));
        if (StrUtil.isNotBlank(rateVale)) {
            return Convert.toDouble(rateVale);
        }
        RateCenter rateCenter = this.getById(sceneId);
        log.info("从数据库中获取到的数据为：{}", rateCenter);
        if(BeanUtil.isEmpty(rateCenter)){
            return 1;
        }
        String percentage = rateCenter.getPercentage();
        if(StrUtil.isEmpty(percentage)){
            return 1;
        }
        if (percentage.contains(":")) {
            String[] split = percentage.split(":");
            percentage = Convert.toStr(Arith.div(Convert.toDouble(split[0]), Convert.toDouble(split[1])));
        }
        redisCache.setCacheObject(getCacheKey(sceneId), percentage);
        return Convert.toDouble(percentage);
    }
    private String getCacheKey(String sceneId) {
        return "payment:".concat(sceneId);
    }
}

